using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Universal.Application.Contracts.Jwt;

namespace Universal.Infrastructure.Jwt;

/// <summary>
/// JWT 令牌服务实现类
/// </summary>
public class JwtTokenService : IJwtTokenService
{
    public readonly JwtSettings _Settings;
    public JwtTokenService(IOptions<JwtSettings> options)
    {
        _Settings = options.Value;
    }

    // 生成jwt令牌
    public string GenerateToken(Guid userId, string username, int? expireMinutes = null)
    {
        var claims = new[]
        {
            new Claim("sub", userId.ToString()), // 使用 "sub" 作为用户ID的claim名称
            new Claim("username", username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_Settings.SecretKey));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        // 使用传入的过期时间，如果没有传入则使用配置中的默认值
        var expirationMinutes = expireMinutes ?? _Settings.ExpireMinutes;

        var token = new JwtSecurityToken(
            issuer: _Settings.Issuer,
            audience: _Settings.Audience,
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(expirationMinutes),
            signingCredentials: creds
        );

        Console.WriteLine($"[JWT] 生成Token，过期时间: {DateTime.UtcNow.AddMinutes(expirationMinutes):yyyy-MM-dd HH:mm:ss} UTC");

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
